package com.dz.lm.service.pay.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.DzCache;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.common.util.WxPay;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.dao.userapply.write.UserApplyDao;
import com.dz.lm.domain.order.Order;
import com.dz.lm.domain.userapply.UserApply;
import com.dz.lm.domain.userproduct.UserProduct;
import com.dz.lm.domain.usersend.UserSend;
import com.dz.lm.service.AbstractService;
import com.dz.lm.service.pay.WxPayService;

import com.dz.lm.service.userapply.UserApplyService;
import com.dz.lm.service.userorder.UserOrderService;
import com.dz.lm.service.userproduct.UserProductService;
import com.dz.lm.service.usersend.UserSendService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.NativeWebRequest;

import javax.annotation.Resource;

@Service
public class WxPayServiceImpl extends AbstractService implements WxPayService {

    public Logger logger = LogManager.getLogger(getClass());

    public WxPayServiceImpl() {
        System.out.println(">>>>>>>>>>>>WxPayServiceImpl");
    }

    @Autowired
    private UserOrderService userOrderService;

    @Resource
    private WxPay wxPay;

    @Resource
    private com.dz.lm.dao.account.read.AccountDao readAccountDao;

    @Resource
    private com.dz.lm.dao.account.write.AccountDao writeAccountDao;

    @Resource
    private com.dz.lm.dao.product.write.ProductDao wProductDao;

    @Resource
    private com.dz.lm.dao.order.read.OrderDao readOrderDao;

    @Resource
    private com.dz.lm.dao.product.read.ProductDao readProductDao;

    @Resource
    private com.dz.lm.dao.order.write.OrderDao writeOrderDao;

    @Resource
    private com.dz.lm.dao.order.read.ProductOrderDao readProductOrderDao;

    @Resource
    private com.dz.lm.dao.order.write.ProductOrderDao writeProductOrderDao;
    @Resource(name = "writeUserApplyDao")
    private UserApplyDao writeUserApplyDao;

    @Resource
    private com.dz.lm.dao.business.write.ApplyProductDao wApplyProductDao;
    @Autowired
    private UserProductService userProductService;
    @Autowired
    private UserSendService userSendService;
    @Autowired
    private UserApplyService userApplyService;
    @Override
    public Map<String, Object> unifiedOrder(Map<String, Object> userInfo) throws ServiceException {

        Map<String, Object> retData = null;
        try {
            Map<String, Object> param = new HashMap<String, Object>();
            Order order = new Order();
            Map<String, Object> account = readAccountDao.qryAccountInfoByUserId(userInfo);
            order.setUserId(Integer.valueOf(userInfo.get("userId").toString()));
            if (account == null || account.get("accountId") == null || "".equals(account.get("accountId"))) {
                //创建账户信息
                userInfo.put("property", "1");//账户性质（1：个人；2：企业）
                userInfo.put("state", "1");//状态（1 正常 2 冻结 3 注销）
                //无数据，新增一条
                writeAccountDao.addAccount(userInfo);
            }
            account = readAccountDao.qryAccountInfoByUserId(userInfo);
            String orderId = getOrderId();
            order.setOrderId(orderId);
            order.setAccountId(Integer.valueOf(account.get("accountId").toString()));
            order.setAmount((Double) userInfo.get("amount"));
            order.setBody(userInfo.get("body").toString());
            if(userInfo.get("gather") != null){
                order.setGatherUserId(StringUtil.getInt(userInfo.get("gather"),0));
            }
            if (userInfo.get("orderType") != null) {
                order.setOrderType(userInfo.get("orderType").toString());//微信
            } else {
                order.setOrderType("2");//微信
            }
            order.setPayType("1");//支付
            order.setState("21");
            /*  ;*/
            Map<String, Object> productMap = new HashMap<String, Object>();
            ;
            if ("00".equals(userInfo.get("agentType")) || "01".equals(userInfo.get("agentType"))) {
                productMap.put("productId", userInfo.get("productId"));
            } else {
                productMap = readProductDao.qryMyMaxProductId(userInfo);
            }
            String type = userInfo.get("type").toString();//根据类型 1 添加产品 2代理返点 3 代理邀请
            if(type .equals("2") && StringUtil.getInt(userInfo.get("agentUid"),0) >0){ //成交时代理返点
                int agentUid = StringUtil.getInt(userInfo.get("agentUid"),0);
                Map gentUser = new HashMap();
                //代理人人账户
                userInfo.put("userId", agentUid);
                Map<String, Object> agnetAccount = readAccountDao.qryAccountInfoByUserId(userInfo);
                if(agnetAccount != null){
                    order.setGatherAccountId(Integer.valueOf(agnetAccount.get("accountId").toString()));
                    order.setGatherUserId(Integer.parseInt(agnetAccount.get("userId").toString()));
                }
            }

            Map map = new HashMap();
            switch (type){
                case "1"://添加产品
                    int productId = StringUtil.getInt(userInfo.get("productId"),0);
                    double agentCost = StringUtil.getDouble(userInfo.get("agentCost"),0);
                    map.put("agentCost",agentCost);
                    map.put("type",1);
                    map.put("productId",productId);
                    map.put("orderId",orderId);
                    param.put("attach", JSON.toJSONString(map));
                    break;
                case "2"://2申请返点
                    int applyId = StringUtil.getInt(userInfo.get("applyId"),0);
                    int agentUid = StringUtil.getInt(userInfo.get("agentUid"),0);
                    int userId = StringUtil.getInt(userInfo.get("userId"),0);
                    double rePoint = StringUtil.getDouble(userInfo.get("rePoint"),0);
                    map.put("type",2);
                    map.put("orderId",orderId);
                    map.put("applyId",applyId);
                    map.put("agentUid",agentUid);
                    map.put("userId",userId);
                    map.put("rePoint",rePoint);
                    param.put("attach", JSON.toJSONString(map));
                    break;
                case "3"://代理邀请
                    int sendId = StringUtil.getInt(userInfo.get("sendId"),0);
                    //小费
                    double fee = StringUtil.getDouble(userInfo.get("amount"),0);
                    map.put("type",3);
                    map.put("sendId",sendId);
                    map.put("orderId",orderId);
                    param.put("attach", JSON.toJSONString(map));
                    break;
                case "4"://下订单 支付
                    int applyId1 = StringUtil.getInt(userInfo.get("applyId"),0);
                    map.put("type",4);
                    map.put("applyId",applyId1);
                    map.put("remark",StringUtil.getInt(userInfo.get("productId"),0));
                    param.put("attach", JSON.toJSONString(map));
                    break;
            }
            writeOrderDao.addOrder(order);

            //andriod weixin
            String platform = StringUtil.getString(userInfo.get("platform"));
            if(!StringUtil.containEmpty(platform)){
                param.put("platform",platform);
            }
            //小程序登录标识
            String wxcode = StringUtil.getString(userInfo.get("wxcode"));
            if(!StringUtil.containEmpty(wxcode)){
                param.put("wxcode",wxcode);
            }
            param.put("out_trade_no", orderId);
            param.put("device_info", userInfo.get("device_info"));
            param.put("body", userInfo.get("body").toString());
            BigDecimal bigAmount = new BigDecimal(userInfo.get("amount").toString());
            BigDecimal big100 = new BigDecimal(100);
            param.put("total_fee", bigAmount.multiply(big100).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
            param.put("spbill_create_ip", userInfo.get("spbill_create_ip"));
            retData = wxPay.unifiedOrder(param);
            long timeStamp = System.currentTimeMillis(); //时间戳
            Map<String, Object> orderMap = new HashMap<String, Object>();
            if ("SUCCESS".equals(retData.get("return_code"))) {
                if(!StringUtil.containEmpty(wxcode) && "wexin".equals(platform)){ //小程序返回时间戳
                    retData.put("timeStamp", timeStamp);
                }
                String sign = wxPay.getSign(retData);
                String reqSign = retData.get("sign") != null ? retData.get("sign").toString() : "";
                logger.info("sign=" + sign + ",regSign=" + reqSign);
                if (!reqSign.equals(sign) && !"wexin".equals(platform)) {
                    retData = new HashMap<String, Object>();
                    retData.put("result", "01");
                    retData.put("message", "订单支付返回值验签失败");
                    return retData;
                }
                if ("SUCCESS".equals(retData.get("result_code"))) {
                    String prepay_id = retData.get("prepay_id").toString();
                    orderMap.put("orderId", orderId);
                    orderMap.put("tradeId", prepay_id);
                    orderMap.put("state", "22");//支付中
                    orderMap.put("returnData", retData.toString());//支付中
                }
	    		/*try {
					writeOrderDao.updateOrder(orderMap);
					orderMap.put("productId", productMap.get("productId"));
					orderMap.put("busPayType", userInfo.get("busPayType"));
					orderMap.put("productClass", userInfo.get("productClass"));
					orderMap.put("payResult", userInfo.get("payResult"));
					writeProductOrderDao.addProductOrder(orderMap);
				} catch (DaoException e) {
					e.printStackTrace();
				}*/
            }
            if("wexin".equals(platform)){ //小程序获取签名
                String s = wxPay.getwxSign(retData);
                retData.put("paySign",s);
            }else {
                retData = wxPay.getOrderParam(retData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retData;
    }

    /**
     * 查询订单
     *
     * @throws ServiceException
     **/
    @Override
    public Map<String, Object> orderquery(Map<String, Object> qryParam) throws ServiceException {
        Map<String, Object> retData = new HashMap<String, Object>();
        try {
            retData = wxPay.orderquery(qryParam);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        Map<String, Object> orderMap = new HashMap<String, Object>();
        if ("SUCCESS".equals(retData.get("return_code"))) {
            String sign = wxPay.getSign(retData);
            String reqSign = retData.get("sign") != null ? retData.get("sign").toString() : "";
            logger.info("sign=" + sign + ",regSign=" + reqSign);
            if (!reqSign.equals(sign)) {
                retData = new HashMap<String, Object>();
                retData.put("result", "01");
                retData.put("message", "订单支付返回值验签失败");
                return retData;
            }
            if ("SUCCESS".equals(retData.get("result_code"))) {
                String prepay_id = retData.get("prepay_id").toString();
//        		orderMap.put("orderId", orderId);
                orderMap.put("tradeId", prepay_id);
                orderMap.put("state", "22");//支付中
                orderMap.put("returnData", retData.toString());//支付中
            }
            try {
                writeOrderDao.updateOrder(orderMap);
            } catch (DaoException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 用户提现
     *
     * @throws ServiceException
     **/
    @Override
    @Transactional
    public Map<String, Object> withdraw(Map<String, Object> userInfo) throws ServiceException {
        Map<String, Object> retData = null;
        Map<String, Object> resultData = null;
        try {
            Map<String, Object> param = new HashMap<String, Object>();
            Order order = new Order();
            Map<String, Object> account = readAccountDao.qryAccountInfoByUserId(userInfo);
            BigDecimal amount = new BigDecimal(account.get("amount").toString());
            BigDecimal cashAmount = new BigDecimal(account.get("cashAmount").toString());
            BigDecimal freezeCashAmount = new BigDecimal(account.get("freezeCashAmount").toString());
            BigDecimal tradeAmount = new BigDecimal(0.00);
            int intCashAmount = cashAmount.intValue();
            //intCashAmount < 50
            if (intCashAmount <= 0) {
                retData = new HashMap<String, Object>();
                retData.put("result", "01");
                retData.put("message", "账户余额不足暂不支持提现!");
                return retData;
            } else if (intCashAmount > 5000) {
                tradeAmount = new BigDecimal(5000.00);
            } else {
                tradeAmount = cashAmount;
            }
            String orderId = getOrderId();
            order.setOrderId(orderId);
            order.setGatherAccountId(Integer.valueOf(account.get("accountId").toString()));
            order.setGatherUserId(Integer.valueOf(userInfo.get("userId").toString()));
            order.setUserId(Integer.valueOf(userInfo.get("userId").toString()));
            order.setAccountId(Integer.valueOf(account.get("accountId").toString()));
            order.setAmount(tradeAmount.doubleValue());
            order.setBody(userInfo.get("desc").toString());
            order.setOrderType("3");
            order.setPayType("1");
            order.setState("31");
            writeOrderDao.addOrder(order);

            cashAmount = cashAmount.subtract(tradeAmount);
            freezeCashAmount = freezeCashAmount.add(tradeAmount);
            userInfo.put("cash_amount", cashAmount.doubleValue());
            userInfo.put("freeze_cash_amount", freezeCashAmount.doubleValue());
            writeAccountDao.updateAccount(userInfo);

            param.put("device_info", userInfo.get("device_info"));
            param.put("desc", userInfo.get("desc").toString());
            param.put("partner_trade_no", orderId);
            param.put("amount", tradeAmount.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).intValue());
            param.put("openid", userInfo.get("openid") != null ? userInfo.get("openid") : "");
            param.put("spbill_create_ip", userInfo.get("spbill_create_ip"));
            if(userInfo.get("wxcode") != null){
                param.put("wxcode",userInfo.get("wxcode").toString());
            }
            retData = wxPay.withdraw(param);
            Map<String, Object> orderMap = new HashMap<String, Object>();
            resultData = new HashMap<String, Object>();
            if ("SUCCESS".equals(retData.get("return_code"))) {
                String state = "";
                orderMap.put("orderId", orderId);
                orderMap.put("transactionId", retData.get("payment_no"));
                orderMap.put("time_end", retData.get("payment_time"));
                orderMap.put("result_code", param.get("result_code"));
                orderMap.put("returnData", retData.toString());
                if ("SUCCESS".equals(retData.get("result_code"))) {
                    state = "33";
                    resultData.put("result", "SUCCESS");
                    resultData.put("message", "提现成功");
                    //增加账户资金变动记录
                    addAccoutSeq(account, orderId, userInfo.get("userId"), amount.toString(), tradeAmount);
                    amount = amount.subtract(tradeAmount);
                    userInfo.put("amount", amount.doubleValue());
                    userInfo.remove("cash_amount");
                    userInfo.put("freeze_cash_amount", 0.00d);
                } else {
                    state = "34";
                    resultData.put("result", "FAIL");
                    resultData.put("message", "提现失败");
                    cashAmount = cashAmount.add(tradeAmount);
                    userInfo.put("cash_amount", cashAmount.doubleValue());
                    userInfo.put("freeze_cash_amount", 0.00d);
                }
                orderMap.put("state", state);
                try {
                    writeOrderDao.updateOrder(orderMap);
                } catch (DaoException e) {
                    e.printStackTrace();
                }
            } else {
                cashAmount = cashAmount.add(tradeAmount);
                userInfo.put("cash_amount", cashAmount.doubleValue());
                userInfo.put("freeze_cash_amount", 0.00d);
            }
            writeAccountDao.updateAccount(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultData;
    }

    private void addAccoutSeq(Map<String, Object> account, String orderId, Object userId, String amount, BigDecimal tradeAmount) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", userId);
        try {
            param.putAll(account);
            param.put("seqFlag", "2");//账户变动方向（1 来帐，2 往帐）
            param.put("changeType", "3");//交易类型（1 充值  2 支付 3 提现 4 返点）
            param.put("preAmount", amount);
            BigDecimal accAmount = new BigDecimal(account.get("amount").toString());
            BigDecimal accCashAmount = new BigDecimal(account.get("cashAmount").toString());
            accAmount = accAmount.subtract(tradeAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
            accCashAmount = accCashAmount.subtract(tradeAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
            param.put("amount", accAmount.doubleValue());
            param.put("cash_amount", accCashAmount.doubleValue());
            param.put("freeze_cash_amount", 0.00d);
            param.put("orderId", orderId);
            writeAccountDao.addAccountSeq(param);
        } catch (DaoException e) {
            e.printStackTrace();
        }
    }

    /**
     * 微信支付结果回调
     *
     * @throws ServiceException
     **/
    @Override
    public Map<String, Object> wxPayCallback(Map<String, Object> param) throws ServiceException {
        Map<String, Object> retData = new HashMap<String, Object>();
        String sign = wxPay.getSign(param);
        String reqSign = param.get("sign") != null ? param.get("sign").toString() : "";
        if (!reqSign.equals(sign)) {
            retData.put("return_code", "FAIL");
            retData.put("return_msg", "PARAMETER ERROR");
            return retData;
        }
        if ("SUCCESS".equals(param.get("return_code"))) {

            String state = "";
            String attach = param.get("attach").toString();
            //微信支付订单号
            String transaction_id = param.get("transaction_id").toString();

            //商户订单号
            String out_trade_no = param.get("out_trade_no").toString();
            System.out.println("进入微信回调 成功时 attach=========================================" + attach);
            //支付完成时间
            String time_end = param.get("time_end").toString();
            //支付状态（支付成功）21 未支付（订单保存未支付）22 支付中 （想支付渠道已提交）23 支付成功	24 支付失败
            state = "23";
            Map map = JSON.parseObject(attach, Map.class);
            int type = StringUtil.getInt(map.get("type"), 0);
            String orderId ="";
            switch (type){
                case 1://添加产品
                    int productId = StringUtil.getInt(map.get("productId"),0);
                    double agentCost = StringUtil.getDouble(map.get("agentCost"),0);
                    UserProduct product = new UserProduct();
                    product.setProductId(productId);
                    product.setAgentCost(agentCost);
                    product.setStatus(2);//发布
                    userProductService.update(product);
                    orderId=StringUtil.getString(map.get("orderId"));
                    break;
                case 2://2代理返点
                    orderId=StringUtil.getString(map.get("orderId"));
                    int applyId = StringUtil.getInt(map.get("applyId"),0);
                    int agentUid = StringUtil.getInt(map.get("agentUid"),0);
                    double rePoint = StringUtil.getDouble(map.get("rePoint"),0);
                    int userId = StringUtil.getInt(map.get("userId"),0);
                    //修改申请状态
                    UserApply apply = new UserApply();
                    apply.setApplyId(applyId);
                    apply.setStatus(3);
                    apply.setAgnetDto(1);
                    apply.setApplyDto(1);
                    try {
                        int i = writeUserApplyDao.updateByPrimaryKeySelective(apply);
                        Map userInfo = new HashMap();
                        //代理人人账户
                        userInfo.put("userId", agentUid);
                        Map<String, Object> account = readAccountDao.qryAccountInfoByUserId(userInfo);
                        userInfo.clear();
                        //原产品人产品人账户
                        userInfo.put("userId", userId);
                        Map<String, Object> Saccount = readAccountDao.qryAccountInfoByUserId(userInfo);
                        //申请人账户流水
                        Order order = new Order();
                        String sbOrderId = getOrderId();
                        order.setOrderId(sbOrderId);
                        order.setUserId(Integer.parseInt(account.get("userId").toString()));
                        order.setAccountId(Integer.valueOf(account.get("accountId").toString()));
                        order.setAmount(rePoint);
                        order.setGatherAccountId(Integer.valueOf(Saccount.get("accountId").toString()));
                        order.setGatherUserId(Integer.parseInt(Saccount.get("userId").toString()));
                        order.setOrderType("7");//申请返点 收入
                        order.setPayType("3");//账户
                        order.setState("13");//冲入
                        writeOrderDao.addOrder(order);
                        //代理人的账户金额
                        BigDecimal agentCostB = new BigDecimal(rePoint);
                        BigDecimal amount = new BigDecimal(account.get("amount").toString());
                        BigDecimal nowAmount = amount.add(agentCostB);
                        BigDecimal cashAmount = new BigDecimal(account.get("cashAmount").toString());
                        BigDecimal nowCashAmount = cashAmount.add(agentCostB);
                        //更新账户
                        account.put("amount", nowAmount);
                        account.put("cash_amount", nowCashAmount);
                        writeAccountDao.updateAccount(account);
                    } catch (DaoException e) {
                        e.printStackTrace();
                    }
                    break;
                case 3://代理邀请
                    int sendId = StringUtil.getInt(map.get("sendId"),0);
                    UserSend send = new UserSend();
                    send.setSendId(sendId);
                    send.setStatus(0);
                    userSendService.update(send);
                    orderId=StringUtil.getString(map.get("orderId"));
                    break;
                case 4://申请订单支付成功
                    orderId=StringUtil.getString(map.get("orderId"));
                    int applyId1 = StringUtil.getInt(map.get("applyId"),0);
                    UserApply userApply = new UserApply();
                    userApply.setApplyId(applyId1);
                    userApply.setStatus(3);
                    userApply.setUpdateTime(DateUtil.getTimeStr(new Date()));
                    userApplyService.update(userApply);
                    try {
                        userOrderService.update("",applyId1,0,"","",0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }

            Map<String, Object> order = new HashMap<String, Object>();
            order.put("orderId", orderId);
            order.put("transactionId", transaction_id);
            order.put("time_end", time_end);
            order.put("result_code", param.get("result_code"));
            order.put("state", state);
            try {
                Long aLong = writeOrderDao.updateOrder(order);
                System.out.println("进入微信回调 成功时 aLong=========================================" + aLong);

				/*writeProductOrderDao.updateProductOrder(order);
				Map<String, Object> productInfo = readProductOrderDao.qryProductInfoByOrderId(order);
				if (productInfo != null && !productInfo.isEmpty()) {
					if ("0".equals(productInfo.get("productClass")) || "1".equals(productInfo.get("productClass"))) {//productClass 产品类别（0：原创产品，1：代理产品，2：申请单支付）
						updateProduct(productInfo);
					} else if ("2".equals(productInfo.get("productClass"))) {
						if ("4".equals(productInfo.get("busPayType"))) {//busPayType:支付类型（1：高亮显示，2：自动刷新，3：高亮及自动刷新, 4：接单支付，5：放款支付）
							Map<String, Object> orderInfo = readOrderDao.qryOrderInfoByorderId(order);
							productInfo.put("applyId", orderInfo.get("applyId"));
							productInfo.put("state", "1");
							productInfo.put("takePayAmount", orderInfo.get("amount"));
							updateApplyProduct(productInfo);
						} else if ("5".equals(productInfo.get("busPayType"))) {
							Map<String, Object> orderInfo = readOrderDao.qryOrderInfoByorderId(order);
							productInfo.put("applyId", orderInfo.get("applyId"));
							productInfo.put("state", "3");
							productInfo.put("payAmount", orderInfo.get("amount"));
							updateApplyProduct(productInfo);
						}
					}
				}*/

            } catch (DaoException e) {
                e.printStackTrace();
            }
            retData.put("return_code", "SUCCESS");
            retData.put("return_msg", "OK");
        }
        return retData;
    }

    private void updateApplyProduct(Map<String, Object> productInfo) {
        try {
            wApplyProductDao.callbackPayResult(productInfo);
        } catch (DaoException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用productId查询相关支付信息
     *
     * @throws ServiceException
     **/
    @Override
    public Map<String, Object> qryProductOrderInfoByProductId(Map<String, Object> param) throws ServiceException {
        try {
            return readProductOrderDao.qryProductOrderInfoByProductId(param);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void updateProduct(Map<String, Object> productInfo) {
        String highLightFlag = "0";
        String autoUpdateFlag = "0";
        Date day = new Date();
        day = DateUtil.getDateAfter3Mon(day, 3);
        long threeMon = day.getTime();
        Timestamp highLightTime = null;
        Timestamp autoUpdateTime = null;
        if ("1".equals(productInfo.get("busPayType"))) {
            highLightFlag = "1";
            highLightTime = new Timestamp(threeMon);
        } else if ("2".equals(productInfo.get("busPayType"))) {
            autoUpdateFlag = "1";
            autoUpdateTime = new Timestamp(threeMon);
        } else if ("3".equals(productInfo.get("busPayType"))) {
            highLightFlag = "1";
            autoUpdateFlag = "1";
            highLightTime = new Timestamp(threeMon);
            autoUpdateTime = new Timestamp(threeMon);
        }
        productInfo.put("highLightFlag", highLightFlag);
        productInfo.put("autoUpdateFlag", autoUpdateFlag);
        productInfo.put("highLightTime", highLightTime);
        productInfo.put("autoUpdateTime", autoUpdateTime);
        try {
            if ("0".equals(productInfo.get("productClass"))) {
                wProductDao.modifyProduct(productInfo);
            } else if ("1".equals(productInfo.get("productClass"))) {
                wProductDao.updateAgentProduct(productInfo);
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
    }

    private String getOrderId() {
        String orderId = "";
        @SuppressWarnings("unchecked")
        List<String> orderIdList = (List<String>) DzCache.getCacheCode("orderId");
        if (orderIdList != null && orderIdList.get(0) != null) {
            orderId = orderIdList.get(0);
            orderIdList.remove(0);
        } else {
            long todayMaxorderId = DzCache.getCacheCode("todayMaxorderId") == null ? 0l : (long) DzCache.getCacheCode("todayMaxorderId");
            long maxId = todayMaxorderId + 100;
            DzCache.setCacheCode("todayMaxorderId", maxId);
            orderIdList = new ArrayList<String>();
            String strTime = DateUtil.getTimeStrFormat(new Date());
            String suffix = "00000000";
            for (long i = todayMaxorderId + 1; i < maxId + 1; i++) {
                suffix = suffix + "" + i;
                suffix = suffix.substring(suffix.length() - 8, suffix.length());
                orderIdList.add(strTime + "" + suffix);
            }
            orderId = orderIdList.get(0);
            orderIdList.remove(0);
            DzCache.setCacheCode("orderId", orderIdList);
        }
        return orderId;
    }
}
